package uk.co.q3c.deplan.client.domain.dag;

import java.util.logging.Logger;

import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Unindexed;

@Unindexed
@Cached(expirationSeconds = 600)
public class Hierarchy<T> extends DAG<T> {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger("Hierarchy");

	public Hierarchy() {
		super();
	}

	public T parentKeyFor(T child) {
		Vertex<T> v = getVertex(child);
		if (v.isRoot()) {
			return null;
		} else {
			return v.getParents()
					.get(0)
					.getKey();
		}
	}

	public void setParentKeyFor(T childKey, T parentKey) throws CycleDetectedException, ChangeInvalidException {
		Vertex<T> vChild = getVertex(childKey);
		// remove existing parent edge
		if (vChild.parentCount() > 0) {
			Vertex<T> vParent = vChild.parents.get(0);
			vParent.removeEdgeTo(vChild);
		}
		// to be sure!
		vChild.clearParents();
		// may have been called to set parent to null
		if (parentKey != null) {
			addEdge(parentKey, childKey);
		}
	}

	public void orderUp(T parentKey, T subTaskKey) {
		Vertex<T> v = getVertex(parentKey);
		if (v == null) {
			logger.warning("requested change of sub task order with null key");
		}
		v.childOrderUp(subTaskKey);
	}

	public void orderDown(T parentKey, T subTaskKey) {
		Vertex<T> v = getVertex(parentKey);
		if (v == null) {
			logger.warning("requested change of sub task order with null key");
		}
		v.childOrderDown(subTaskKey);
	}

	public boolean isAtomic(T task) {
		Vertex<T> v = getVertex(task);
		return !v.hasChildren();
	}

}
